<?php
namespace app\admin\controller;

use app\BaseController;
use app\Request;
use app\common\model\mysql\User;

class Login extends BaseController
{
    //定义全局受保护变量
    protected $userobj;

    //实例化
    public function __construct()
    {
        $this->userobj = new User();
    }

    //渲染登录页面
    public function index(request $request)
    {
        if (session("adminUser")) {
            return redirect(url("/admin/home"));
        }
        return view('login');
    }

    /*
    *登录
    *传值方式 post
    *参数 username 用户名 pwd 密码 captcha 验证码
     */
    public function login(request $request)
    {
        $data['username'] = $request->post('username','','trim');
        $data['password'] = $request->post('password','','trim');
        $captcha = $request->post('captcha','','trim');

        //验证非空
        if ($data['username'] == '' || $data['password'] == '' || $captcha == '') {
            return json(['code'=>1,'msg'=>'必填项不能为空','data'=>'']);
        }

        //验证码
        if(!captcha_check($captcha)){
            return json(['code'=>1,'msg'=>'验证码不正确','data'=>'']);
        };

        //密码加密
        $data['password'] = md5($data['password']);

        $res = $this->userobj->login($data);

        if (!$res) {
            return json(['code'=>1,'msg'=>'账号或密码有误','data'=>'']);
        }

        //更新表
        $update = [
            "last_login_time"=>time(),
            "last_login_ip"=>$request->ip(),
            "update_time"=>time(),
        ];

        $result = $this->userobj->upda($res['id'],$update);

        if (empty($res)) {
            return json(['code'=>1,'msg'=>'登录失败','data'=>'']);
        }

        //记录session
        session("adminUser",$res);

        return json(['code'=>0,'msg'=>'登录成功','data'=>$res],200);
    }
}